package fr.cephb.joperon.webapp.tag;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.TagSupport;


/**
 * Tag writing a Google analytics tracker
 * @author lindenb
 *
 */
public class UrchinTag  extends TagSupport
	{
	private static final long serialVersionUID = 1L;
	private String websiteid=null;
	
	public void setWebsiteid(String websiteid) {
		this.websiteid = websiteid;
		}
	
	public String getWebsiteid() {
		return websiteid;
		}
	
	@Override
	public int doStartTag() throws JspException
		{
		return SKIP_BODY;
		}
	
	@Override
	public int doEndTag() throws JspException
		{
		
		try {
			String serverName=super.pageContext.getRequest().getServerName();
			if(getWebsiteid()==null || serverName==null || serverName.contains("localhost"))
				{
				super.pageContext.getOut().write("<!-- Google analytics skipped -->\n");
				}
			else
				{
				super.pageContext.getOut().write(
						"<!-- start google analytics -->\n"+
						"<script type=\"text/javascript\">\n"+
						"var gaJsHost = ((\"https:\" == document.location.protocol) ? "+
						"\"https://ssl.\" : \"http://www.\");\n"+
						"document.write(unescape(\"%3Cscript src='\" + gaJsHost + "+
						"\"google-analytics.com/ga.js' type='text/javascript'%3E%3C/script%3E\"));\n"+
						"</script>\n"+
						"<script type=\"text/javascript\">\n"+
						"try {\n"+
						"var pageTracker = _gat._getTracker(\""+ getWebsiteid() +"\");\n"+
						"pageTracker._trackPageview();\n"+
						"} catch(err) {}</script>\n"+
						"<!-- end google analytics -->\n"
						)
						;
				
				}
			} 
		catch (Exception e)
			{
			pageContext.getServletContext().log( "Urchin tag failed",e);
			}
		return EVAL_PAGE;
		}
	@Override
	public void release() {
		this.websiteid=null;
		}
	}
